package com.dcits.electronic_account.service.impl;

import com.dcits.electronic_account.bean.BankAccount;
import com.dcits.electronic_account.bean.Flow;
import com.dcits.electronic_account.bean.VirtualAccount;
import com.dcits.electronic_account.mapper.RechargeMapper;
import com.dcits.electronic_account.mapper.TransferAccountsMapper;
import com.dcits.electronic_account.service.RechargeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author: YHC
 * @Date: 2022/6/25
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class RechargeServiceImpl implements RechargeService {

    @Resource
    RechargeMapper rechargeMapper;

    @Resource
    TransferAccountsMapper transferAccountsMapper;


    @Override
    public VirtualAccount searchVirByUserId(Integer userId) {
        return rechargeMapper.searchVirByUserId(userId);
    }

    @Override
    public BankAccount searchBankByNumber(String cardNumber) {
        return rechargeMapper.searchBankByNumber(cardNumber);
    }


    @Override
    public void rechargeDo(VirtualAccount user, BankAccount card, BigDecimal amount) {
        if(rechargeMapper.updateCardBalance(card.getBalance().subtract(amount),card.getBankCardNumber())<1) throw new RuntimeException("更改金额失败");
        if(rechargeMapper.updateUserBalance(user.getBalance().add(amount),user.getUserId())<1) throw new RuntimeException("添加流水失败");
        Flow flow = new Flow();
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        flow.setAmount(amount);
        flow.setPayer(card.getId().toString());
        flow.setPayee(user.getUserId().toString());
        flow.setType(0);
        flow.setTime(dateFormat.format(date));
        if(transferAccountsMapper.addFlow(flow)<1) throw new RuntimeException("添加流水失败");
    }


}
